package com.tianruan.psychological.moduls.sys.user.api;

import com.tianruan.psychological.common.response.VResponse;
import com.tianruan.psychological.moduls.sys.user.entry.MOAuth2AccessToken;
import com.tianruan.psychological.moduls.sys.user.entry.dto.UserDTO;
import com.tianruan.psychological.moduls.sys.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2020-09-12 09:57
 * @PS
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;
    @Autowired
    private IUserService userService;

    /**
     * Oauth2登录认证
     */
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public VResponse<Object> postAccessToken(Principal principal,
                                             @RequestParam Map<String, String> parameters,
                                             HttpServletResponse response) throws HttpRequestMethodNotSupportedException {
//        OAuth2AccessToken accessToken = tokenEndpoint.getAccessToken(principal, parameters).getBody();
//        if (accessToken != null) {
//            Map<String, ?> stringMap = checkTokenEndpoint.checkToken(accessToken.getValue());
//            System.out.println();
//        }


        // 登录用户如果想唯一一个地方登录，可以用refresh_token刷新之前的token

        try {
            String grantType = parameters.get("grant_type");
            OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
            // 修改账号密码登录返回的token信息
            if ("password".equals(grantType)) {
                MOAuth2AccessToken moAuth2AccessToken = new MOAuth2AccessToken();
                moAuth2AccessToken.setAccessToken(oAuth2AccessToken.getValue());
                moAuth2AccessToken.setRefreshToken(oAuth2AccessToken.getRefreshToken().getValue());
                moAuth2AccessToken.setExpiresIn(oAuth2AccessToken.getExpiresIn());
                moAuth2AccessToken.setTokenType(oAuth2AccessToken.getTokenType());
                moAuth2AccessToken.setScope(oAuth2AccessToken.getScope());


                String username = parameters.get("username");
                UserDTO user = userService.getUserPermissionByNo(username);
                user.setPassword(null);
                moAuth2AccessToken.setUser(user);

                // 保存登录信息

                return VResponse.success(moAuth2AccessToken);
            } else {
                return VResponse.success(oAuth2AccessToken);
            }
        } catch (InvalidGrantException ige) {
            if ("invalid_grant".equals(ige.getOAuth2ErrorCode())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return VResponse.error(HttpServletResponse.SC_UNAUTHORIZED, "用户名密码错误");
            }
            return VResponse.error(1000, ige.getOAuth2ErrorCode() + ige.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
